package com.gzhryc.net_marketing.api;

import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.account.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

public class CloudPayAccountAPIService {

    static Logger log = Logger.getLogger(CloudPayAccountAPIService.class);

    private static CloudPayAccountAPIService me;

    public static CloudPayAccountAPIService self() {
        if(me == null) {
            me = new CloudPayAccountAPIService();
        }
        return me;
    }

    private CloseableHttpClient httpClient;
    private String cloudApiHttpDomain;

    public void initial(String cloudApiHttpDomain) {
        this.httpClient = HttpClients.createDefault();
        this.cloudApiHttpDomain = cloudApiHttpDomain;
    }

    public CloudPayAccountInfoResponse getAccountInfo(Long accountId, String accountToken) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/info.data").build();

            CloudPayAccountInfoRequest apiReq = new CloudPayAccountInfoRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付账号信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountInfoResponse apiResp = JsonTools.fromJson(str, CloudPayAccountInfoResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付账号信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountOperateListResponse findAccountOperateList(Long accountId,String accountToken,Integer pageNo,Integer pageLimit) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/operate/list.data").build();

            CloudPayAccountOperateListRequest apiReq = new CloudPayAccountOperateListRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setPageNo(pageNo);
            apiReq.getBody().setPageLimit(pageLimit);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付账号流水信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountOperateListResponse apiResp = JsonTools.fromJson(str, CloudPayAccountOperateListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付账号流水信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountDepositOrderListResponse findAccountDepositOrderList(Long accountId, String accountToken, Integer pageNo, Integer pageLimit) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/deposit/order/list.data").build();

            CloudPayAccountDepositOrderListRequest apiReq = new CloudPayAccountDepositOrderListRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setPageNo(pageNo);
            apiReq.getBody().setPageLimit(pageLimit);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付账号充值订单信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountDepositOrderListResponse apiResp = JsonTools.fromJson(str, CloudPayAccountDepositOrderListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付账号充值订单信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountOrderListResponse findAccountOrderList(Long accountId,String accountToken,Integer type,Integer pageNo,Integer pageLimit) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/order/list.data").build();

            CloudPayAccountOrderListRequest apiReq = new CloudPayAccountOrderListRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setType(type);
            apiReq.getBody().setPageNo(pageNo);
            apiReq.getBody().setPageLimit(pageLimit);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付账号订单信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountOrderListResponse apiResp = JsonTools.fromJson(str, CloudPayAccountOrderListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付账号订单信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountWithdrawOrderListResponse findAccountWithdrawOrderList(Long accountId,String accountToken,Integer pageNo,Integer pageLimit) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/withdraw/order/list.data").build();

            CloudPayAccountWithdrawOrderListRequest apiReq = new CloudPayAccountWithdrawOrderListRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setPageNo(pageNo);
            apiReq.getBody().setPageLimit(pageLimit);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付账号取款订单信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountWithdrawOrderListResponse apiResp = JsonTools.fromJson(str, CloudPayAccountWithdrawOrderListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付账号取款订单信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 获取取款用户信息
     * @param accountId
     * @param accountToken
     * @param receivingType
     * @return
     */
    public CloudPayAccountWithdrawPayeeListResponse findAccountWithdrawPayeeList(Long accountId,String accountToken,Integer receivingType) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/withdraw/payee/list.data").build();

            CloudPayAccountWithdrawPayeeListRequest apiReq = new CloudPayAccountWithdrawPayeeListRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setReceivingType(receivingType);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付账号取款人信息返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountWithdrawPayeeListResponse apiResp = JsonTools.fromJson(str, CloudPayAccountWithdrawPayeeListResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付账号取款人信息错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountRechargeResponse recharge(Long accountId,String accountToken,Integer payType,Integer money,String tradeNo) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/recharge.do").build();

            CloudPayAccountRechargeRequest apiReq = new CloudPayAccountRechargeRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setPayType(payType);
            apiReq.getBody().setMoney(money);
            apiReq.getBody().setTradeNo(tradeNo);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("云支付账号充值返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountRechargeResponse apiResp = JsonTools.fromJson(str, CloudPayAccountRechargeResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("云支付账号充值错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public DefaultAPIResponse cancelRecharge(Long accountId, String accountToken,String tradeNo) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/recharge/cancel.do").build();

            CloudPayAccountRechargeCancelRequest apiReq = new CloudPayAccountRechargeCancelRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setTradeNo(tradeNo);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("取消云支付账号充值返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    DefaultAPIResponse apiResp = JsonTools.fromJson(str, DefaultAPIResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("取消云支付账号充值错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountPayResponse pay(CloudPayAccountPayRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/pay.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountPayResponse apiResp = JsonTools.fromJson(str, CloudPayAccountPayResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountSearchOrderInfoResponse searchOrder(Long accountId,String accountToken,String businessTradeNo) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/order/search.do").build();

            CloudPayAccountSearchOrderInfoRequest apiReq = new CloudPayAccountSearchOrderInfoRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);
            apiReq.getBody().setBusinessTradeNo(businessTradeNo);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("查询云支付订单返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountSearchOrderInfoResponse apiResp = JsonTools.fromJson(str, CloudPayAccountSearchOrderInfoResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("查询云支付订单错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountSettlementResponse settlement(CloudPayAccountSettlementRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/settlement.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付结算返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountSettlementResponse apiResp = JsonTools.fromJson(str, CloudPayAccountSettlementResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付结算错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountWithdrawResponse withdraw(CloudPayAccountWithdrawRequest apiReq) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/withdraw.do").build();

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("获取云支付取款返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountWithdrawResponse apiResp = JsonTools.fromJson(str, CloudPayAccountWithdrawResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("获取云支付取款错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public CloudPayAccountWithdrawPayeeAddResponse addWithdrawPayee(Long accountId, String accountToken) {
        CloseableHttpResponse response = null;
        try {
            URI uri = new URIBuilder(cloudApiHttpDomain + "/market/cloud_api/v1/payAccount/withdraw/payee/add.do").build();

            CloudPayAccountWithdrawPayeeAddRequest apiReq = new CloudPayAccountWithdrawPayeeAddRequest();
            apiReq.getBody().setAccountId(accountId);
            apiReq.getBody().setAccountToken(accountToken);

            StringEntity strEntity = new StringEntity(JsonTools.toJson(apiReq), ContentType.create("application/json", Consts.UTF_8));

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(strEntity);

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                log.info("云支付添加提现用户返回：" + str);
                if(StringUtils.isNotBlank(str)) {
                    CloudPayAccountWithdrawPayeeAddResponse apiResp = JsonTools.fromJson(str, CloudPayAccountWithdrawPayeeAddResponse.class);
                    return apiResp;
                }
            }
        } catch(Exception e){
            log.error("云支付添加提现用户错误", e);
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
